const fs = require('fs');
const path = require('path');

const logDir = path.join(__dirname, '..', 'logs');

// 确保日志目录存在
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir);
}

/**
 * 将消息记录到文件中
 * @param {string} message - 要记录的消息
 * @param {string} [level='info'] - 日志级别 ('info' 或 'error')
 */
function log(message, level = 'info') {
  const now = new Date();
  const date = now.toISOString().split('T')[0];
  const logFilePath = path.join(logDir, `${date}.log`);

  const timestamp = now.toISOString();
  const formattedMessage = `[${timestamp}] [${level.toUpperCase()}] ${message}\n`;

  fs.appendFile(logFilePath, formattedMessage, (err) => {
    if (err) {
      // 如果写入日志文件失败，则将错误输出到标准错误流
      process.stderr.write(`写入日志文件失败: ${err}\n`);
    }
  });
}

module.exports = {
  log,
  info: (message) => log(message, 'info'),
  error: (message) => log(message, 'error'),
};